package com.mk.legoscans2.data;

import java.util.ArrayList;
import java.util.List;

public class LocalFavoritesRepository implements FavoritesRepository {

	private ApplicationPreferences _applicationPreferences;
	
	public LocalFavoritesRepository(ApplicationPreferences applicationPreferences)
	{
		_applicationPreferences = applicationPreferences;
	}
	
	public List<String> getFavorites() {
		String favoritesString = _applicationPreferences.getFavorites();
		String[] favArr = favoritesString.split(",");
		
		ArrayList<String> favorites = new ArrayList<String>();
		
		for (String s : favArr) {
			if(s != null && !s.equals(""))
				favorites.add(s);
		}
		return favorites;
	}

	public boolean toggleFavorite(String scanId) {
		boolean isFavorite;
		ArrayList<String> favorites = new ArrayList<String>(getFavorites());
		if(isFavorite(scanId))
		{
			favorites.remove(scanId);
			isFavorite = false;
		}
		else
		{
			favorites.add(scanId);
			isFavorite = true;
		}
		
		_applicationPreferences.setFavorites(convertToString(favorites));
		
		return isFavorite;
	}

	public boolean isFavorite(String scanId) {
		List<String> favorites = getFavorites();
		for (String fav : favorites) {
			if(scanId.equals(fav))
				return true;
		}
		return false;
	}

	private String convertToString(List<String> favorites)
	{
		String s = "";
		if(favorites.size() == 0)
			return s;
		
		for (String fav : favorites) {
			s += fav + ",";
		}
		
		return s.substring(0, s.length() - 1);
	}
}
